// 权限控制
import router from './router'
import store from './store'
import { asyncRoutes } from '@/router/asyncRoutes'

// 获取一级权限标识
function getFirstRoutePermission(permission) {
  const firstPermArr = permission.map(item => {
    return item.split(':')[0]
  })
  // 去重
  return Array.from(new Set(firstPermArr))
}

// 获取二级权限标识
function getSecondRoutePermission(permission) {
  const secondPermArr = permission.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  // 去重
  return Array.from(new Set(secondPermArr))
}

// 根据一级二级权限标识，动态路由筛选
function getRoutes(firstPermission, secondPermission, asyncRoutes) {
  // 判断当前登入人是否是管理员
  if (firstPermission.includes('*')) {
    return asyncRoutes
  }
  const firstRoutes = asyncRoutes.filter(item => firstPermission.includes(item.permission))
  const routes = firstRoutes.map(item => {
    return {
      ...item,
      children: item.children.filter(child => secondPermission.includes(child.permission))

    }
  })
  return routes
}

const WHITE_LIST = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token
  // 有token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 拿到用户权限信息
      // 筛选
      const permission = await store.dispatch('menu/getUserPermission')
      // console.log(permission)

      // 根据权限标识 筛选对应的一级路由标识
      const firstPermission = getFirstRoutePermission(permission)
      // console.log('一级权限标识', firstPermission)

      // 二级权限标识
      const secondPermission = getSecondRoutePermission(permission)
      // console.log('二级权限标识', secondPermission)

      // 导入动态路由进行筛选
      const routes = getRoutes(firstPermission, secondPermission, asyncRoutes)
      // console.log(routes)

      // 把筛选出来的路由添加到路由表中，展示在左侧
      routes.forEach(item => router.addRoute(item))

      store.commit('menu/setMenuList', routes)
    }
  } else {
    // 没有token
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
